/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

package au.com.lastweekend.desktop.freedesktop;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;

import javax.swing.Action;

import org.apache.log4j.Logger;

import au.com.lastweekend.desktop.Desktop;
import au.com.lastweekend.desktop.FileSelector;
import au.com.lastweekend.jim.util.IniReader;
import au.com.lastweekend.jim.util.IniSection;


/**
 * See www.freedesktop.org various specifications.
 * 
 * @author grant@lastweekend.com.au
 * @version $Id$
 */
public class FreeDesktop implements Desktop {

    private static final String DEFAULT_THEME = "hicolor";
    private static final int DEFAULT_SMALL_ICON_SIZE = 16;
    private static final String APPLICATIONS = "applications";
    private static final String MIMEINFO_CACHE = "mimeinfo.cache";
    private static final String XDG_DATA_DIRS = "XDG_DATA_DIRS";
    private static final String MIME_CACHE_SECTION = "MIME Cache";
    private static final Logger LOG = Logger.getLogger(FreeDesktop.class);
    private static final String XDG_X_ICON_THEME = "XDG_X_ICON_THEME";
    private IconTheme iconTheme;
    int smallIconSize = DEFAULT_SMALL_ICON_SIZE;

    public static boolean isSupported() {

        return System.getenv(XDG_DATA_DIRS) != null;
    }

    public FreeDesktop() {

        this(null, null);
    }

    /**
     * 
     * @param theme -
     *            theme name, null for default
     * @param dataDirs -
     *            See {@link #setDataDirs(String)}, null to use the XDG_DATA_DIRS environment variable
     */
    public FreeDesktop(String theme, String dataDirs) {

        if (theme == null) {
            // Custom environment variable that knows the users current Icon
            // theme, spec doesn't say
            // how an application should determine the current theme
            theme = System.getenv(XDG_X_ICON_THEME);
            if (theme == null) {
                theme = DEFAULT_THEME;
                LOG.warn("XDG_X_ICON_THEME not set, using default " + theme);
            }
        }

        if (dataDirs == null) {
            dataDirs = System.getenv(XDG_DATA_DIRS);
        }

        LOG.info(String.format("Using datadirs=%s, theme=%s", dataDirs, theme));

        // Must set data dirs first
        setDataDirs(dataDirs);
        setIconTheme(theme);

    }

    private Collection<File> dataDirs = Collections.emptyList();

    /**
     * A ":" separated string of absolute pathnames to directories to search for mimetypes, themese etc...
     * 
     * @param dirsString
     */
    public final void setDataDirs(String dirsString) {

        dataDirs = new ArrayList<File>();
        if (dirsString != null) {
            String[] xdgDataDirs = dirsString.split(":");
            for (String dir : xdgDataDirs) {
                File dataDir = new File(dir);
                if (dataDir.exists()) {
                    dataDirs.add(dataDir);
                }
            }
        }
    }

    public Collection<Action> getActions(String mimetype, FileSelector fileSelector) {

        Collection<Action> actions = new ArrayList<Action>();
        Collection<DesktopEntry> desktopEntries = findApplications(mimetype);
        for (DesktopEntry desktopEntry : desktopEntries) {
            Action action = desktopEntry.getAction(fileSelector);
            if (action != null) {
                actions.add(action);
            }
        }

        return actions;

    }

    private Collection<DesktopEntry> findApplications(String mimetype) {

        List<DesktopEntry> apps = new ArrayList<DesktopEntry>();

        Collection<File> baseDirs = getDataDirs();
        for (File baseDir : baseDirs) {

            File appsDir = new File(baseDir, APPLICATIONS);
            File mimeCache = new File(appsDir, MIMEINFO_CACHE);

            if (!mimeCache.exists()) {
                continue;
            }

            String jpegEntry = null;
            try {
                IniReader iniReader = new IniReader(mimeCache);
                IniSection iniSection = iniReader.readSection();
                if (iniSection != null && iniSection.getName().equals(MIME_CACHE_SECTION)) {
                    jpegEntry = iniSection.getKey("image/jpeg");
                }
            } catch (IOException e) {
                LOG.warn("Unable to read applications from mimecache " + mimeCache.getAbsolutePath(), e);
            }

            if (jpegEntry == null) {
                continue;
            }

            StringTokenizer tokenizer = new StringTokenizer(jpegEntry, ";");

            while (tokenizer.hasMoreTokens()) {
                String desktopEntryFileName = tokenizer.nextToken();
                File desktopEntryFile = new File(appsDir, desktopEntryFileName);
                DesktopEntry desktopEntry;
                try {
                    desktopEntry = new DesktopEntry(this, desktopEntryFile);
                    apps.add(desktopEntry);
                } catch (IOException e) {
                    LOG.warn("Bad desktop entry " + desktopEntryFile.getAbsolutePath(), e);
                }
            }
        }

        return apps;

    }

    final Collection<File> getDataDirs() {

        return dataDirs;
    }

    String getThemeIcon(String icon) {

        return iconTheme.findIcon(icon, smallIconSize);

    }

    public final void setIconTheme(String theme) {

        try {
            iconTheme = new IconTheme(getDataDirs(), theme);
        } catch (IOException e) {
            iconTheme = IconTheme.NULL_THEME;
            LOG.warn("Unable to load theme - " + theme, e);
        }
    }

    public int getSmallIconSize() {

        return smallIconSize;
    }

    public void setSmallIconSize(int smallIconSize) {

        this.smallIconSize = smallIconSize;
    }
}
